import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPClientPlus1 {
    private DatagramSocket socket = null;
    private String serverIp;
    private  int serverPork;
    public UDPClientPlus1(String serverIp,int serverPork) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPork = serverPork;
    }
    private void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入请求指令->");
            String request = scanner.next();
            if (request.equals("exit")){
                System.out.println("退出程序");
            }
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                                                              InetAddress.getByName(serverIp),serverPork);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            String log = String.format("req:%s ,res:%s ",request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPClientPlus1 udpClientPlus1 = new UDPClientPlus1("127.0.0.1",9999);
        udpClientPlus1.start();
    }
}
